<template>
  <div class="app-container">
    <!-- 卡片展示区域 -->
    <el-row :gutter="20" class="card-container">
      <el-col
        v-for="(dictItem, index) in dict.type.audit_business_type"
        :key="dictItem.value"
        :span="6"
        class="card-item"
      >
        <el-card class="audit-node-card" shadow="hover">
          <div slot="header" class="clearfix card-header">
            <span>业务类型 {{ dictItem.label }}</span>
          </div>
          <div class="card-body">
            <div class="card-item-row">
              <span class="card-item-label">值：</span>
              <span>{{ dictItem.value }}</span>
            </div>
            <div class="card-item-row">
              <span class="card-item-label">标签：</span>
              <span>{{ dictItem.label }}</span>
            </div>
          </div>
          <div class="card-footer">
            <el-button
              size="mini"
              type="primary"
              @click="handleSetProcess(dictItem)"
            >设置审批流程</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 当没有数据时显示 -->
    <div v-if="dict.type.audit_business_type.length === 0 && !loading" class="no-data">
      <p>暂无业务类型数据</p>
    </div>

    <!-- 设置审批流程对话框 -->
    <el-dialog :title="'设置审批流程 - ' + currentBusinessType.label" :visible.sync="processOpen" width="600px" append-to-body>
      <el-table
        :data="processList"
        style="width: 100%"
        border
        row-key="rowKey"
        ref="processTable"
        v-loading="processLoading"
      >
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column label="节点审核模式" width="200">
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.auditMode">
              <el-radio
                v-for="dict in dict.type.audit_mode"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </template>
        </el-table-column>
        <el-table-column label="审批角色" width="200">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.auditRoleId"
              placeholder="请选择审批角色"
              clearable
              @change="handleAuditRoleChange(scope.$index, scope.row.auditRoleId)"
            >
              <el-option
                v-for="role in getAvailableRoles(scope.$index)"
                :key="role.roleId"
                :label="role.roleName"
                :value="role.roleId"
                :disabled="isRoleSelected(role.roleId, scope.$index)"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <!-- <el-table-column label="抄送角色" width="400">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.copyRoleIds"
              placeholder="请选择抄送角色"
              multiple
              clearable
              class="copy-role-select"
              :popper-append-to-body="false"
              ref="copyRoleSelect"
              :style="getCopyRoleStyle(scope.row.copyRoleIds)"
            >
              <el-option
                v-for="role in roleList"
                :key="role.roleId"
                :label="role.roleName"
                :value="role.roleId"
              ></el-option>
            </el-select>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="handleDeleteProcess(scope.$index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddProcess">添加节点</el-button>
        <el-button type="primary" @click="submitProcess">确 定</el-button>
        <el-button @click="processOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAuditNode, getAuditNode, delAuditNode, addAuditNode, updateAuditNode, saveAuditNode, listAuditNodeNoPage } from "@/api/system/auditNode"
import { listRole } from "@/api/system/role"

export default {
  name: "AuditNode",
  dicts: ['audit_business_type', 'audit_mode'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审批流配置表格数据
      auditNodeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        auditBusinessType: null,
        auditMode: null,
        auditRoleId: null,
        copyRoleIds: null,
        auditOrder: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        auditBusinessType: [
          { required: true, message: "审核业务类型，取字典不能为空", trigger: "change" }
        ],
        auditMode: [
          { required: true, message: "节点的审核模式，取字典不能为空", trigger: "change" }
        ],
        auditRoleId: [
          { required: true, message: "审批角色id不能为空", trigger: "change" }
        ],
        auditOrder: [
          { required: true, message: "审核顺序不能为空", trigger: "blur" }
        ],
      },
      // 设置审批流程弹窗显示控制
      processOpen: false,
      // 审批流程表格loading
      processLoading: false,
      // 当前业务类型
      currentBusinessType: {},
      // 审批流程列表
      processList: [],
      // 角色列表
      roleList: []
    }
  },
  created() {
    this.getList()
    this.getRoleList()
  },
  methods: {
    /** 查询审批流配置列表 */
    getList() {
      this.loading = true
      listAuditNode(this.queryParams).then(response => {
        this.auditNodeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询角色列表 */
    getRoleList() {
      listRole({ pageSize: 100, pageNum: 1 }).then(response => {
        this.roleList = response.rows
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        auditNodeId: null,
        auditBusinessType: null,
        auditMode: null,
        auditRoleId: null,
        copyRoleIds: null,
        auditOrder: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.auditNodeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加审批流配置"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const auditNodeId = row.auditNodeId || this.ids
      getAuditNode(auditNodeId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改审批流配置"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.auditNodeId != null) {
            updateAuditNode(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAuditNode(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const auditNodeIds = row.auditNodeId || this.ids
      this.$modal.confirm('是否确认删除审批流配置编号为"' + auditNodeIds + '"的数据项？').then(function() {
        return delAuditNode(auditNodeIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/auditNode/export', {
        ...this.queryParams
      }, `auditNode_${new Date().getTime()}.xlsx`)
    },
    /** 设置审批流程按钮操作 */
    handleSetProcess(businessType) {
      if (!businessType || !businessType.value) {
        this.$modal.msgWarning("未找到业务类型值")
        return
      }
      this.currentBusinessType = businessType
      this.processOpen = true
      this.processList = []
      this.fetchProcessList(businessType.value)
    },
    /** 添加审批流程节点 */
    handleAddProcess() {
      this.processList.push(this.createEmptyProcessNode())
    },
    /** 删除审批流程节点 */
    handleDeleteProcess(index) {
      if (this.processList.length === 1) {
        this.$modal.msgWarning("至少保留一个审批节点")
        return
      }
      this.processList.splice(index, 1)
    },
    /** 处理审批角色变化 */
    handleAuditRoleChange(index, roleId) {
      // 角色变化时不需要特殊处理，限制主要在选项层面
      console.log('审批角色变化:', index, roleId);
    },
    /** 获取当前可选的角色列表 */
    getAvailableRoles(currentIndex) {
      return this.roleList;
    },
    /** 检查角色是否已被选择（除当前行外） */
    isRoleSelected(roleId, currentIndex) {
      if (!roleId) return false;
      // 检查除当前行外是否已存在相同角色
      return this.processList.some((item, index) => {
        return index !== currentIndex && item.auditRoleId === roleId;
      });
    },
    /** 查询当前业务类型的审批流程配置 */
    fetchProcessList(auditBusinessType) {
      this.processLoading = true
      listAuditNodeNoPage(auditBusinessType)
        .then(response => {
          const list = Array.isArray(response.data) ? response.data : []
          if (list.length === 0) {
            this.processList = [this.createEmptyProcessNode()]
            return
          }
          const sortedList = list.slice().sort((a, b) => {
            const orderA = a.auditOrder || 0
            const orderB = b.auditOrder || 0
            return orderA - orderB
          })
          this.processList = sortedList.map((item, index) => ({
            rowKey: this.generateRowKey(item.auditNodeId || index),
            auditNodeId: item.auditNodeId || null,
            auditMode: item.auditMode || '',
            auditRoleId: this.tryParseNumber(item.auditRoleId),
            copyRoleIds: this.transformCopyRoleIds(item.copyRoleIds),
            auditOrder: item.auditOrder || index + 1
          }))
        })
        .catch(error => {
          console.error('查询审批流程失败:', error)
          this.$modal.msgError('查询审批流程失败')
          this.processList = [this.createEmptyProcessNode()]
        })
        .finally(() => {
          this.processLoading = false
        })
    },
    /** 创建空的审批流程节点 */
    createEmptyProcessNode() {
      return {
        rowKey: this.generateRowKey(),
        auditNodeId: null,
        auditMode: '',
        auditRoleId: null,
        copyRoleIds: [],
        auditOrder: this.processList.length + 1
      }
    },
    /** 生成表格唯一 key */
    generateRowKey(seed) {
      const base = seed !== undefined ? seed : Date.now()
      return `process-${base}-${Math.random().toString(16).slice(2, 8)}`
    },
    /** 处理抄送角色 id */
    transformCopyRoleIds(copyRoleIds) {
      if (!copyRoleIds) {
        return []
      }
      if (Array.isArray(copyRoleIds)) {
        return copyRoleIds
      }
      return String(copyRoleIds)
        .split(',')
        .map(item => item.trim())
        .filter(item => item !== '')
        .map(item => this.tryParseNumber(item))
    },
    /** 转换数字 */
    tryParseNumber(value) {
      if (value === null || value === undefined || value === '') {
        return null
      }
      const num = Number(value)
      return Number.isNaN(num) ? value : num
    },
    /** 提交审批流程设置 */
    submitProcess() {
      if (!this.processList.length) {
        this.$modal.msgError('请至少添加一个审批节点')
        return
      }
      // 校验必填项
      for (let i = 0; i < this.processList.length; i++) {
        const node = this.processList[i];
        if (!node.auditMode) {
          this.$modal.msgError(`第${i + 1}行节点审核模式不能为空`);
          return;
        }
        if (!node.auditRoleId) {
          this.$modal.msgError(`第${i + 1}行审批角色不能为空`);
          return;
        }
      }

      // 构造提交数据
      const submitData = this.processList.map((item, index) => {
        return {
          auditBusinessType: this.currentBusinessType.value,
          auditMode: item.auditMode,
          auditRoleId: item.auditRoleId,
          copyRoleIds: Array.isArray(item.copyRoleIds) ? item.copyRoleIds.join(',') : (item.copyRoleIds || ''),
          auditOrder: index + 1  // 添加审核顺序字段，从1开始递增
        }
      });

      // 调用保存接口
      saveAuditNode(submitData).then(response => {
        this.$modal.msgSuccess("保存成功");
        this.processOpen = false;
        this.getList(); // 保存成功后刷新列表
      }).catch(error => {
        console.error("保存失败:", error);
        this.$modal.msgError("保存失败");
      });
    },
    /** 计算抄送角色下拉宽度 */
    getCopyRoleStyle(copyRoleIds) {
      const baseWidth = 260;
      const maxWidth = 720;
      if (!Array.isArray(copyRoleIds) || !copyRoleIds.length) {
        return { width: `${baseWidth}px` };
      }
      const text = copyRoleIds
        .map(id => {
          const role = this.roleList.find(r => r.roleId === id);
          return role ? role.roleName : '';
        })
        .filter(Boolean)
        .join('、');
      const calcWidth = 16 * text.length + 140;
      const width = Math.min(Math.max(calcWidth, baseWidth), maxWidth);
      return { width: `${width}px` };
    }
  }
}
</script>

<style scoped lang="scss">
.card-container {
  margin-bottom: 20px;
}

.card-item {
  margin-bottom: 20px;
}

.audit-node-card {
  height: 50%;

  .card-header {
    font-weight: bold;
  }

  .card-body {
    min-height: 150px;
  }

  .card-item-row {
    margin-bottom: 10px;
    display: flex;
    align-items: center;

    .card-item-label {
      font-weight: bold;
      width: 80px;
      display: inline-block;
    }
  }

  .card-footer {
    text-align: right;
    padding-top: 10px;
  }
}

.no-data {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

::v-deep .copy-role-select .el-select__tags {
  display: inline-flex;
  flex-wrap: nowrap;
  align-items: center;
  height: 34px;
  overflow: hidden;
}

::v-deep .copy-role-select .el-tag {
  margin-bottom: 0;
  flex-shrink: 0;
}

::v-deep .copy-role-select .el-select__tags > span {
  display: inline-flex;
  align-items: center;
}

::v-deep .copy-role-select .el-select__input {
  flex: 0 0 auto;
  height: 28px;
  line-height: 28px;
}

</style>
